// 运维首页 新增巡视计划
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { tenantUserEnum } from '~/store/oam/typings'
import type { FormInstance } from 'element-plus'
import type {
  patrolsTableListDataItemType,
  formPatrolsUpdateStateType,
  patrolsUpdateStateType
} from './typings'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElRow,
  ElCol,
  ElForm,
  ElLink,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElButton,
  ElIcon,
  ElMessage
} from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash'
import { handleTrim } from '~/utils/util'
import { SPAN_STYLE_DOUBLE } from '~/utils/const'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import MapView from '../map/MapView' // 地图
import AddAreaList from './AddAreaList' // 新增台区
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'PatrolsUpdate',
  props: {
    // 标题
    // 新增巡视 传:  "新增巡视"
    // 编辑工单 传:  "编辑巡视"
    title: {
      type: String,
      default: ''
    },
    showPatrolsUpdate: {
      type: Boolean,
      default: false
    }
  },
  emits: ['handleClose'],
  setup(props, { emit }) {
    const store = useStore()
    // 初始值
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const ruleFormRef = ref<FormInstance>()
    const mapViewRef = ref() // 地图

    // form
    const formState = reactive<formPatrolsUpdateStateType>({
      form: {
        time: []
      }
    })
    const orderState = useVuexGetters('order', ['tenantUserSelectList', 'tenantUserEnum'])

    // 其他值
    const state = reactive<patrolsUpdateStateType>({
      showAddAreaList: false, // 新增台区弹窗
      selecteds: [] // 新增的台区
    })

    onMounted(() => {
      store.dispatch('order/GetTenantUserSelectList')
    })

    // methods
    const submit = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate(async (valid) => {
        if (state.selecteds?.length === 0) {
          ElMessage({ type: 'warning', message: '台区列表不能为空' })
        } else {
          if (valid) {
            // 去输入的前后空格
            formState.form.name = handleTrim(formState.form.name ?? '')

            const info = JSON.parse(localStorage.getItem('saber-userInfo')!) // 获取本地缓存
            // 新增时, 待传的数据
            const add = {
              addCours: state.selecteds,
              name: formState.form.name,
              leadUserId: formState.form.leadUserId,
              beginTime: formState.form.time[0],
              endTime: formState.form.time[1],
              leadDeptId: info.content.deptId
            }
            // 使用新增巡视的接口
            const res = await store.dispatch('patrol/PostAddPatrolsPlan', add)
            if (res?.code === 200) {
              formState.form = { time: [] }
              emit('handleClose')
            }
          }
        }
      })
    }

    const beforeCloseDialog = (formEl: FormInstance | undefined) => {
      formState.form = { time: [] }
      emit('handleClose')
      if (!formEl) return
      formEl.resetFields()
    }

    // 点击台区列表的操作列(地图), 在地图显示该台区地址
    const lookPointOnMap = (row: patrolsTableListDataItemType) => {
      try {
        state.showAddAreaMap = true
        state.markers = { lng: row.longitude!, lat: row.latitude! }
        setTimeout(() => {
          mapViewRef.value.setMarkersByPropsMarkers()
        }, 100)
      } catch (error) {
        ElMessage({
          message: '暂无当前地点坐标噢',
          type: 'warning'
        })
      }
    }

    // 删除刚新增的台区
    const delSome = () => {
      const element = cloneDeep(proSaasTableRef.value?.selecteds)
      const selectedsArr = element.map((item: { coursId: string }) => item.coursId) // 存所有id
      state.selecteds = state.selecteds?.filter((item) => selectedsArr.indexOf(item.coursId) === -1) // 过滤调已存在的
    }

    // 新增台区是否显示
    const handleAddAreaListClose = () => {
      state.showAddAreaList = false
    }

    // 要新增的台区
    const selectedArea = (value: patrolsTableListDataItemType[]) => {
      if (!state.selecteds || state.selecteds?.length === 0) {
        state.selecteds = value
      } else {
        let ifMessage = false // 是否显示提示消息
        for (const item of value) {
          let ifAdd = true // 是否添加该台区
          for (const element of state.selecteds!) {
            if (item.coursId === element.coursId) {
              ifAdd = false
              break
            }
          }

          if (ifAdd) {
            state.selecteds?.push(item) // 把ifAdd为真的部分赋给list
          } else {
            ifMessage = true
          }
        }

        if (ifMessage) {
          // 无论重了多少个, 弹框都只弹一次
          ElMessage({
            message: '不能添加重复的台区列表哦, 未重复的已添加成功',
            type: 'warning'
          })
        }
      }
    }

    const columns: TableColumnProps<patrolsTableListDataItemType>[] = [
      {
        label: '台区名称',
        prop: 'coursName',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '所属工区',
        prop: 'coursArea',
        minWidth: 180,
        align: 'center'
      },
      {
        label: '台区地址',
        prop: 'coursAddress',
        minWidth: 180,
        align: 'center'
      },
      {
        label: '操作',
        prop: 'options',
        minWidth: 180,
        align: 'center',
        render: ({ row }) => {
          return (
            <ElLink type="warning" onClick={() => lookPointOnMap(row)}>
              地图
            </ElLink>
          )
        }
      }
    ]

    return () => {
      return (
        <ElDialog
          modelValue={props.showPatrolsUpdate}
          width="80%"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={() => beforeCloseDialog(ruleFormRef.value)}
          title={props.title}
          append-to-body
        >
          <ElRow>
            <ElCol span={10}>
              <ElForm ref={ruleFormRef} model={formState.form} label-width="100px">
                <ElRow>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      label="巡视名称："
                      prop="name"
                      rules={[{ required: true, message: '请输入巡视名称', trigger: 'change' }]}
                    >
                      <ElInput
                        v-model={formState.form.name}
                        placeholder="请输入巡视名称"
                        clearable
                      ></ElInput>
                    </ElFormItem>
                  </ElCol>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      label="责任人："
                      prop="leadUserId"
                      rules={[{ required: true, message: '请选择责任人', trigger: 'change' }]}
                    >
                      <ElSelect
                        v-model={formState.form.leadUserId}
                        placeholder="请选择责任人"
                        clearable
                      >
                        {orderState.tenantUserSelectList?.value?.map((item: tenantUserEnum) => (
                          <ElOption key={item?.id} label={item?.name} value={item?.id} />
                        ))}
                      </ElSelect>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol>
                    <ElFormItem
                      label="计划时间："
                      prop="time"
                      rules={[{ required: true, message: '请选择计划时间', trigger: 'change' }]}
                    >
                      <ElDatePicker
                        v-model={formState.form.time}
                        value-format="YYYY-MM-DD"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      ></ElDatePicker>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <div class={styles['patrol-area']}>
                  <span style="color: red;">* </span>
                  <span>台区列表</span>
                  <div class={styles['patrol-area-btn']}>
                    <ElButton
                      type="primary"
                      onClick={() => {
                        state.showAddAreaList = true
                      }}
                    >
                      <ElIcon>
                        <Plus />
                      </ElIcon>
                      &nbsp;新增
                    </ElButton>
                    <ElButton type="primary" plain onClick={delSome}>
                      <ElIcon>
                        <Minus />
                      </ElIcon>
                      &nbsp;删除
                    </ElButton>
                  </div>
                  <ProSaasTable<patrolsTableListDataItemType> // 台区列表
                    ref={proSaasTableRef}
                    columns={columns}
                    needPagination={false}
                    data={state.selecteds}
                    hasSelection
                  />
                </div>
              </ElForm>
            </ElCol>
            <ElCol span={3}></ElCol>
            <ElCol span={10}>
              <div class={styles['patrolUpdate-map']}>
                <MapView
                  id="patrolsUpdateMap"
                  ref={mapViewRef}
                  markers={state.markers}
                  needMultipleMarker={false} // 单点标记
                  orderMarker={false} // 不为工单地图
                />
              </div>
            </ElCol>
          </ElRow>
          <div class={styles['patrol-submitAndCancel-btn']}>
            <ElButton type="primary" size="default" onClick={() => submit(ruleFormRef.value)}>
              确 定
            </ElButton>
            <ElButton size="default" onClick={() => beforeCloseDialog(ruleFormRef.value)}>
              取 消
            </ElButton>
          </div>

          {/* 新增台区 */}
          <AddAreaList
            showAddAreaList={state.showAddAreaList}
            onHandleClose={handleAddAreaListClose}
            onSelectedArea={selectedArea}
          />
        </ElDialog>
      )
    }
  }
})
